package com.estar.assistsurvy.thread;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

import com.estar.assistsurvy.constant.Constants;
import com.google.gson.Gson;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaseThread extends Thread {
//基本网络请求线程类，用于各种网络请求线程类继承
	public String result,json,url_str;
	public Context context;
	public Handler handler;
	public Gson gson;
	public Message msg;

	public BaseThread(Context context, Handler handler) {
		super();
		this.context = context;
		this.handler = handler;
		gson=new Gson();
		msg=handler.obtainMessage();
	}


	public void postRequest(String url_str,String json){
		final OkHttpClient client=new OkHttpClient.Builder()
				.connectTimeout(30, TimeUnit.SECONDS)
				.readTimeout(30, TimeUnit.SECONDS)
				.build();
		
		RequestBody body=RequestBody.create(Constants.JSON, json);
		Request request=new Request.Builder()
				.url(url_str)
				.post(body)
				.build();

		Response response=null;
		try {
			response=client.newCall(request).execute();
			if(response.isSuccessful()){
				result=response.body().string();
			}else{
				
				msg.obj="当前服务器忙，请稍后再试";
				msg.what=-1;
				msg.sendToTarget();
			}
		}catch (SocketTimeoutException e) {
			msg.obj="访问超时，请稍后再试";
			msg.what=-1;
			msg.sendToTarget();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			msg.obj="当前服务器忙，请稍后再试";
			msg.what=-1;
			msg.sendToTarget();
		}
//		response.close();
	}
}
